<template>
  <el-card>
    <!-- 标题 -->
    <div slot="header">
      <span class="el-card-title">快捷入口</span>
      <i
        v-show="!isPanelSetIcon"
        class="el-icon-close"
        style="float: right; padding: 3px 0"
        @click="deletePanelItem"
      ></i>
      <el-button v-show="isPanelSetIcon" style="float: right; padding: 3px 0" type="text" @click="setQuickMenu">编辑</el-button>
    </div>
    <!-- 新建按钮 -->
    <div class="often-control-box">
            <el-row>
              <el-col style="margin-bottom: 0px;padding: 6px 5px;" :span="12" 
                v-for="(item,index) in quickMenu" :key="index">
                <div>
                  <el-button style="padding: 0px;" type="text" :icon="item.source" @click="open(item)">{{item.name}}</el-button>
                </div>
              </el-col>
            </el-row>
            <el-row v-if='selfData.length > 0'>
              <el-divider content-position="center" ><span style="color:#666666;font-size:14px;">自定义导航</span></el-divider>
              <el-row>
                <el-col style="margin-bottom: 0px;padding: 6px 5px;" :span="12" 
                  v-for="(item,index) in selfData" :key="index">
                  <div>
                    <el-button style="padding: 0px;" type="text"  @click="open(item)">{{item.name}}</el-button>
                  </div>
                </el-col>
              </el-row>
            </el-row>
    <!-- 
      设置快捷入口
    -->
      <el-dialog title="快捷入口定义" width='60%'  :append-to-body='true' :close-on-click-modal='false' :visible.sync="setFastEntryDialog">
        <div v-if="fullscreenLoading" style="width:100%; text-align:center;font-size:30px;top:100px;position:relative;z-index:5000">
            <i  class="el-icon-loading"></i>
        </div>
        <el-tabs  v-model="activeTabName" type="border-card">
          <el-tab-pane label="菜单入口" name="menuPrivilege">
            <el-tree  
              style="height:300px;overflow:auto;"
              :data="menuTreeData"
              show-checkbox
              :expand-on-click-node='false'
              check-on-click-node = 'true'
              node-key="id"
              ref="menuTree"
              highlight-current
              :default-checked-keys="treeValue"
              @check="getCheckedNodes"
              :props="menuTreeProps">
            </el-tree>
          </el-tab-pane>
          <el-tab-pane label="自定义导航" name="interfacePrivilege">
            <avue-crud 
                  ref="selfCrud" 
                  :option="options" 
                  :data="selfData" 
                  @row-del="delSelfMenu"
                  @row-update="addUpdate">
              </avue-crud>
          </el-tab-pane>
        </el-tabs> 
        <div slot="footer" class="dialog-footer">
          <el-button size="small" type="primary" id="copyBtn" @click="handleSaveMenu($event)" icon="el-icon-check">保 存</el-button>
          <el-button size="small" @click="setFastEntryDialog = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </el-card>
</template>

<script>
import {queryGeneralFlowProcessRecordListPage} from '@/api/general/flow/generalFlowProcessRecordApi';
import {saveOrUpdateSysUserSetting,saveSysUserSetting,querySysUserSetting} from '@/api/system/sysUserSettingApi';
import {buryingPoint} from '@/util/buryingPoint'

import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
export default {
  props: ['id', 'panelSetIcon'],
  data () {
    return {
      panelId: this.id,
      isPanelSetIcon: this.panelSetIcon,
      
      //快捷入口定义
      quickMenu: [],
      setFastEntryDialog:false,
      activeTabName: 'menuPrivilege',
      menuTreeData: [],
      menuTreeProps: {
        children: 'children',
        label: 'name'
      },
      treeValue: [], 
      isTabChange: false,
      currentTabName: '',
      dialogTitle: '',
      // 自定义标签表格
      selfData:[],
      options:{
        addBtn:false,
        editBtn:false,
        addRowBtn:true,
        saveBtn: false,
        cancelBtnText: '删除',
        cellBtn:true,
        menuWidth:70,
        column: [
          {
            label:'标题',
            prop: 'name',
            type:'input',
            cell: true,
            width:150,
            rules: [
              {
                required: true,
                message: '请输入标题',
                trigger: 'blur'
              }
            ]
          },{
            label:'网址',
            prop: 'path',
            type:'input',
            cell: true,
            rules: [
              {
                required: true,
                message: '请输入网址',
                trigger: 'blur'
              }
            ]
          },{
            label:'新窗口',
            prop: 'newWindow',
            type:'switch',
            value: true,
            cell: true,
            width:60
          },{
            label:'带租户号',
            prop: 'isTenant',
            type:'switch',
            value: true,
            cell: true,
            width:70
          },{
            label:'活动',
            prop: 'meta',
            type:'switch',
            hide: true,
          }]
      },
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 1
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    }
  },
  computed: {
    ...mapGetters(['website','userInfo','orgTree','permission','menu']),
    labelKey() {
      return this.website.menu.props.label;
    },
    pathKey() {
      return this.website.menu.props.path;
    },
    iconKey() {
      return this.website.menu.props.icon;
    },
    childrenKey() {
      return this.website.menu.props.children;
    },
    nowTagValue() {
      return this.$router.$avueRouter.getValue(this.$route);
    }
  },
  methods: {
    /**
     * 获取树形菜单
     */
    setQuickMenu(){
      //获取已设置列表
      this.treeValue = this.$getStore({name:  this.userInfo.userId +'QuickMenu'});
      this.activeTabName = 'menuPrivilege';
      this.setFastEntryDialog = true,
      this.menuTreeData = [];
      for(var i=0; i<6;i++){
        let menu = this.$getStore({name: this.userInfo.userId+'menu'+i});
        if(menu && menu.length > 0){
          this.menuTreeData.push.apply(this.menuTreeData, menu);
        }
      }
      // 获取已设置列表
      this.treeValue = [];
      if(this.quickMenu){
        this.quickMenu.forEach(element => {
          this.treeValue.push(element.id);
        });
      }
      if(this.$getStore({name:  this.userInfo.userId +'selfNaviMenu'})){
        this.selfData = this.$getStore({name:  this.userInfo.userId +'selfNaviMenu'});
      }
    },
    
    /**
     * 保存
     */
    handleSaveMenu(){
      let allCheckList = [];
      this.$refs.menuTree.getCheckedNodes().forEach(element => {
        if(element.children.length == 0){
          if(JSON.stringify(allCheckList).indexOf(element.path) < 0){
            allCheckList.push({
              id: element.id,
              name: element.name,
              path: element.path,
              meta:  element.meta,
              source: element.source,
              children: []
            })
          }
        }
      });
      this.$setStore({name: this.userInfo.userId +'QuickMenu', content: allCheckList});
      this.$setStore({name: this.userInfo.userId +'selfNaviMenu', content: this.selfData});
      this.quickMenu = allCheckList;

      //修改写入数据库
      const loading = this.$loading({
        lock: true,
        text: '处理中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      });

      this.reqParams.singleBody = {
        id: this.userInfo.userId,
        userName: this.userInfo.userName,
        realName: this.userInfo.realName,
        tenantId: this.userInfo.tenantId,
        selfDefMenuContent: this.quickMenu,
        selfDefNaviContent: this.selfData
      };
      this.commonData = reqCommonMsg(this.reqParams)
      saveOrUpdateSysUserSetting(this.commonData).then(() => {
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '保存成功!'
        });
        this.setFastEntryDialog = false,
        loading.close();
      }, error => {
        this.$message({
          customClass:'zZindex',
          type: 'error',
          message: '保存失败!'
        });
        //this.$console.log(error);
        loading.close();
      });
    },
    /**
     * 添加便签
     */
    addUpdate(form,index,done,loading){
      form.meta={
        i18n: 'cache',
        keepAlive: true
      }
      this.$setStore({name: this.userInfo.userId +'selfNaviMenu', content: this.selfData});
      done();
    },
    /**
     * 删除便签
     */
    delSelfMenu(row,index){
      this.selfData.splice(index,1);
      this.$setStore({name: this.userInfo.userId +'selfNaviMenu', content: this.selfData});
    },
    /**
     * 打开页面
     */
    open(item) {
      buryingPoint(item,'self');  
      if (this.screen <= 1) this.$store.commit('SET_COLLAPSE');
      this.$router.$avueRouter.group = item.group;
      this.$router.$avueRouter.meta = item.meta;
      if(item.newWindow && item.newWindow == true){
        if(item.isTenant && item.isTenant == true){
          window.open(item.path+'tenantId='+localStorage.getItem('tenantId'));
        }
        else{
          window.open(item.path);
        }
      }
      else {
        this.$router.push({
          path: this.$router.$avueRouter.getPath({
            name: item[this.labelKey],
            src: item[this.pathKey],
            i18n: (item.meta || {}).i18n
          }),
          query: item.query
        });
      }
    },
    // 删除面板项发送事件
    deletePanelItem () {
      this.$emit('deletePanelItemEvent', this.panelId)
    }
  },
  created(){
    if(this.$getStore({name:  this.userInfo.userId +'QuickMenu'})){
      this.quickMenu = this.$getStore({name:  this.userInfo.userId +'QuickMenu'});
      //this.$router.$avueRouter.formatRoutes(this.quickMenu, true);
    }
    if(this.$getStore({name:  this.userInfo.userId +'selfNaviMenu'})){
      this.selfData = this.$getStore({name:  this.userInfo.userId +'selfNaviMenu'});
    }
  },
  mounted() {
    
  }
}
</script>

<style>
.el-card {
  height: 100%;
}
.el-icon-close {
  font-size: 1.2em;
  cursor: pointer;
}
.el-card-title {
  font-weight: bold;
}
.often-control-box {
  grid-template-columns: repeat(2, 50%);
}
.often-control-box .often-control-item {
  height: 50px;
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #424e5c;
}
.often-control-item > i {
  color: #396aff;
  margin-right: 10px;
  font-size: 1.5em;
}

.often-control-box .avue-crud__menu {
    display: none !important;
}
.often-control-box .el-card__body{
  padding: 10px 5px !important;
}
</style>
